package ar.edu.unrn.lia.bean.datamodel;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.inject.Inject;

import org.primefaces.model.LazyDataModel;
import org.primefaces.model.SortMeta;
import org.primefaces.model.SortOrder;

import ar.edu.unrn.lia.model.Inquilino;
import ar.edu.unrn.lia.service.InquilinoService;

public class LazyInquilinoDataModel extends LazyDataModel<Inquilino> {

	/**
	 * 
	 */
	private static final long serialVersionUID = -1964840046533377804L;

	
	private List<Inquilino> list;

	@Inject
	InquilinoService entityService;

	public InquilinoService getEntityService() {
		return entityService;
	}

	public LazyInquilinoDataModel(InquilinoService entityService) {
		super();
		this.entityService = entityService;
	}

	@Override
	public List<Inquilino> load(int startingAt, int maxPerPage,
			List<SortMeta> multiSortMeta, Map<String, String> filters) {
		try {
			Map<String, Boolean> sorts = new HashMap<String, Boolean>();
			if (multiSortMeta != null) {
				for (SortMeta sortMeta : multiSortMeta) {
					sorts.put(sortMeta.getSortField(), sortMeta.getSortOrder()
							.name().equals(SortOrder.ASCENDING.toString()));
				}
			}

			list = getEntityService().getList(startingAt, maxPerPage, filters,
					sorts);

		} catch (Exception e) {
			FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_ERROR,"Error Consulta",e.getMessage());
			FacesContext.getCurrentInstance().addMessage(null, msg);
			e.printStackTrace();
			list = new ArrayList<Inquilino>(0);
		}

		// set the total of list
		if (getRowCount() <= 0) {
			setRowCount(getEntityService().getCount(filters).intValue());
		}

		// set the page dize
		setPageSize(maxPerPage);

		return list;
	}

	@Override
	public Object getRowKey(Inquilino entity) {
		return entity.getId();
	}

	@Override
	public Inquilino getRowData(String entityId) {
		Integer id = Integer.valueOf(entityId);

		for (Inquilino entity : list) {
			if (id.equals(entity.getId())) {
				return entity;
			}
		}

		return null;
	}

	public void setEntityService(InquilinoService entityService) {
		this.entityService = entityService;
	}

	public List<Inquilino> getList() {
		return list;
	}

	public void setList(List<Inquilino> list) {
		this.list = list;
	}

}